<?php 
class ioLoginSina
{

    public function __construct(){
    }
    function login($appid, $callback) {
        $_SESSION['rurl'] = $_REQUEST ["loginurl"];
        $_SESSION ['state'] = md5 ( uniqid ( rand (), true ) ); //CSRF protection
        $params=array(
            'response_type'=>'code',
            'client_id'=>$appid,
            'state'=>$_SESSION ['state'],
            'scope'=>$scope,
            'redirect_uri'=>$callback
        );
        $login_url = 'https://api.weibo.com/oauth2/authorize?'.http_build_query($params);
        wp_redirect($login_url, 302);
        exit;
    }
    function callback($appid,$appkey,$path){
        if ($_REQUEST ['state'] == $_SESSION ['state']) {
            $params=array(
                'grant_type'=>'authorization_code',
                'code'=>$_REQUEST ["code"],
                'client_id'=>$appid,
                'client_secret'=>$appkey,
                'redirect_uri'=>$path
            ); 
            $url = 'https://api.weibo.com/oauth2/access_token?' . http_build_query($params);
            $response = wp_remote_post($url, null);
    
            $body = wp_remote_retrieve_body($response);

            if(preg_match('/\{(.*)\}/', $body, $matches)){
                $msg = json_decode(trim($matches[0]));
                if(isset($msg->error)){
                    wp_die($msg->error_code.': '.$msg->error, __('获取微博 Access Token 失败', 'i_theme'), array('response'=>403));
                }
            }else{
                wp_die('微博服务器返回了不正确的响应', __('获取微博 Access Token 失败', 'i_theme'), array('response'=>403));
            }
            $_SESSION['sina_access_token'] = $msg->access_token;
            $_SESSION['sina_openid'] = $msg->uid;
        }else{
            echo ("The state does not match. You may be a victim of CSRF.");
            exit;
        }
    }
    function get_user_info() { 
        $get_user_info = "https://api.weibo.com/2/users/show.json?uid=".$_SESSION['sina_openid']."&access_token=".$_SESSION['sina_access_token'];
        $response = wp_remote_get($get_user_info);
        $body = wp_remote_retrieve_body($response);

        if(preg_match('/\{(.*)\}/', $body, $matches)){
            $msg = json_decode(trim($matches[0]));
            if(isset($msg->error)){
                wp_die($msg->error_code.': '.$msg->error, __('获取微博用户信息失败', 'i_theme'), array('response'=>403));
            }
        }else{
            wp_die('微博服务器返回了不正确的响应', __('获取微博用户信息失败', 'i_theme'), array('response'=>403));
        }

        return $msg;
    }
    function get_user_id() {
        $get_user_id = "https://api.weibo.com/2/account/get_uid.json?access_token=".$_SESSION['sina_access_token'];
        $response = wp_remote_get($get_user_id);
        $body = wp_remote_retrieve_body($response);

        if(preg_match('/\{(.*)\}/', $body, $matches)){
            $msg = json_decode(trim($matches[0]));
            if(isset($msg->error)){
                wp_die($msg->error_code.': '.$msg->error, __('获取微博用户 UID 失败', 'i_theme'), array('response'=>403));
            }
        }else{
            wp_die('微博服务器返回了不正确的响应', __('获取微博用户 UID 失败', 'i_theme'), array('response'=>403));
        }
        return $msg;
    }
    function use_db(){
        global $wpdb;
        $uidArray =  $this->get_user_id();
        if(isset($_SESSION['sina_openid']) && isset($_SESSION['sina_access_token']) && $uidArray->uid == esc_sql($_SESSION['sina_openid'])){ 

            if(is_user_logged_in()){
                $userid = wp_get_current_user()->ID;
                $user_ID = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE sina_id='".esc_sql($_SESSION['sina_openid'])."'");
                if($user_ID && $user_ID != $userid)
                { 
                    wp_die("该账号已经存在，不能绑定到当前账号！", __('绑定失败', 'i_theme'), array('response'=>403));
                }
                $wpdb->query("UPDATE $wpdb->users SET sina_id = '".esc_sql($_SESSION['sina_openid'])."' WHERE ID = '$userid'");
                $uinfo =  $this->get_user_info();
                update_user_meta($userid, 'sina_avatar', $uinfo->avatar_large);
                update_user_meta($userid, 'sina_name', $uinfo->screen_name);
                update_user_meta($userid, 'sina_openid', esc_sql($_SESSION['sina_openid']));
            }

            $user_ID = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE sina_id='".esc_sql($_SESSION['sina_openid'])."'");
            if ($user_ID) {
                wp_set_auth_cookie($user_ID,true,is_ssl());
                wp_redirect($_SESSION['rurl']); 
                if(get_user_meta($user_ID, 'sina_avatar' )){
                    $uinfo = $this->get_user_info();
                    update_user_meta($user_ID, 'sina_avatar', $uinfo->avatar_large);
                    update_user_meta($user_ID, 'sina_name', $uinfo->screen_name);
                    update_user_meta($user_ID, 'sina_openid', esc_sql($_SESSION['sina_openid']));
                } 
                exit();
            }else{
                $prename = 'io';
                $extname = rand(1000000,9999998);
                $login_name = $prename.$extname;
                if(username_exists($login_name)){
                    while(username_exists($login_name)){ $extname++; }
                    $login_name = $prename.$extname;
                }
                $pass = wp_generate_password(); 
                $uinfo = $this->get_user_info();
                $username = $uinfo->screen_name;
                $description = $uinfo->description;
                $userdata=array(
                    'user_login' => $login_name,
                    'user_email' => $login_name.'@io.com',
                    'display_name' => $username,
                    'user_pass' => $pass,
                    'nickname' => $username,
                    'description'=> $description,
                    'role' => get_option('default_role')
                );
                $user_id = wp_insert_user( $userdata );
                if ( is_wp_error( $user_id ) ) {
                    echo $user_id->get_error_message();
                }else{
                    $ff = $wpdb->query("UPDATE $wpdb->users SET sina_id = '".$_SESSION['sina_openid']."' WHERE ID = '$user_id'");
                    if ($ff) {
                        update_user_meta($user_id, 'avatar', $uinfo->avatar_large);
                        update_user_meta($user_id, 'sina_avatar', $uinfo->avatar_large);
                        update_user_meta($user_id, 'sina_name', $uinfo->screen_name);
                        update_user_meta($user_id, 'name_change', 1);
                        update_user_meta($user_id, 'sina_openid', esc_sql($_SESSION['sina_openid']));
                        update_user_meta($user_id, 'avatar_type', 'sina');
                        wp_set_auth_cookie($user_id,true,is_ssl());
                        wp_redirect($_SESSION['rurl']);
                    }          
                }
                exit();
            }
        }
    } 
}
?>